/*
 * Created on Oct 4, 2003
 *
 * Mihai Postelnicu
 *
 */
package ro.gateway.aida.struts.action;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.tiles.actions.TilesAction;

import ro.gateway.aida.db.PersistenceManager;
import ro.gateway.aida.db.PersistenceToken;
import ro.gateway.aida.stats.SectorLineChart;
import ro.gateway.aida.stats.SectorPieChart;
import ro.gateway.aida.stats.StatsDB;
import ro.gateway.aida.stats.StatsHolder;
import ro.gateway.aida.usr.Arbiter;
import ro.gateway.aida.usr.Perms;
import ro.gateway.aida.utils.BugTracker;
import ro.xblue.translator.LanguageBean;
import ro.xblue.translator.TranslatorUtils;


/**
 * @author Mihai Postelnicu
 * StatsAction
 *
 * */
public class SectorStatsAction extends TilesAction {
    public ActionForward execute(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) {
        try {
            ServletContext sc = getServlet().getServletContext();
            PersistenceToken token = PersistenceManager.tokenLookup(sc);
            String mode = request.getParameter("mode");
            String parent = request.getParameter("parent");
            StatsDB sdb = StatsDB.getManager(token);
            LanguageBean lang_bean = TranslatorUtils.getCurrentLanguage(request,
                    sc);
            String lang = lang_bean.language;

            int parent_id;

            if (parent != null) {
                parent_id = Integer.parseInt(parent);
            } else {
                parent_id = -1;
            }

            Arbiter ar = Arbiter.getManager(token);
            boolean show = false;

            if (ar.canDo(request, Perms.SHOW_UNAPPROVED))
                show = true;

            StatsHolder sh = sdb.getSortedSectorStats(lang, parent_id,show);

            if (sh.size() != 0)
                request.setAttribute("sstats", sh);

            if ("widget".equals(mode)) {
                return mapping.findForward("stats.txt.sector.widget");
            }

            if ("pie".equals(mode)) {
                SectorPieChart spc = new SectorPieChart(sh);
                request.setAttribute("pieData", spc);

                return mapping.findForward("stats.charts.sector.pie");
            }

            if ("line".equals(mode)) {
                SectorLineChart slc = new SectorLineChart();
                request.setAttribute("pageViews", slc);

                return mapping.findForward("stats.charts.sector.line");
            }

            return mapping.findForward("stats.txt.sector.list");
        } catch (Exception e) {
            BugTracker.publishBug(e, request);

            return mapping.findForward("fail");
        }
    }
}
